<script setup>
import { reactive, ref, watch } from 'vue'
import GoodsImage from './components/GoodsImage.vue'
import CitySelector from './components/CitySelector.vue'
import InputNumber from './components/InputNumber.vue'
import GoodsCarousel from './components/GoodsCarousel.vue'
import NoticeList from './components/NoticeListView.vue'
import ReviewAndDetails from './components/ReviewAndDetails.vue'
import HotSelling from './components/HotSellingView.vue'
import { getGoods, getRecommands, getHotSellingAPI, addToCart as addToCartAPI } from '@/api/detail'
import { useRoute } from 'vue-router'
import { ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import collectGoods from '@/utils/collectGoods'
import { lazyApi } from '@/utils/lazy'
import router from '@/router'
import { useUserStore } from '@/stores'
const store = useUserStore()
import { useHeadGoodsStore } from '@/stores/head'
const store1 = useHeadGoodsStore()

const route = useRoute()
const loading = ref(true)

//获取商品详情的数据
const goodsDetail = ref([])
const nag1 = ref()
const nag2 = ref()
const idstr1 = ref()
const idstr2 = ref()

const getGoodsDetail = async (id = route.params.id) => {
  const res = await getGoods(id)
  goodsDetail.value = res.data.result
  nag1.value = res.data.result.categories[1].name
  nag2.value = res.data.result.categories[0].name
  idstr1.value = res.data.result.categories[1].id
  idstr2.value = res.data.result.categories[0].id
  idstr1.value = res.data.result.categories[1].id
  idstr2.value = res.data.result.categories[0].id
  loading.value = false
}
getGoodsDetail()

const recommendsDetail = ref([])
const getRecommendsDetail = async id => {
  const reb = await getRecommands(id)
  recommendsDetail.value = reb.data.result
}
const { target: recommendTarget } = lazyApi(getRecommendsDetail)

//定义响应式的选中效果变量
const currIndex = ref(-1)
const currIndex2 = ref(-1)

//获取选中颜色或样式后的数据
const colorValue = ref([])
const colorValueFun = (name, i) => {
  if (currIndex.value === i) {
    currIndex.value = -1
    colorValue.value = []
  } else {
    currIndex.value = i
    colorValue.value = name
  }
}

const sizeValue = ref([])
const sizeValueFun = (name, i) => {
  if (currIndex2.value === i) {
    currIndex2.value = -1
    sizeValue.value = []
  } else {
    currIndex2.value = i
    sizeValue.value = name
  }
}

// 加入购物车函数
const addToCart = async () => {
  if (!store.isLogined) {
    router.push('/login')
    ElMessage.error('请先登录')
  } else {
    const idstr = ref('') //存储获取到的id信息
    for (var i = 0; i < goodsDetail.value.skus.length; i++) {
      if (sizeValue.value.length > 0) {
        if (goodsDetail.value.skus[i].specs[0].name === '尺码') {
          if (
            goodsDetail.value.skus[i].specs[0].valueName === sizeValue.value &&
            goodsDetail.value.skus[i].specs[1].valueName === colorValue.value
          ) {
            idstr.value = goodsDetail.value.skus[i].id
            break
          }
        }
        if (goodsDetail.value.skus[i].specs[0].name === '颜色') {
          if (
            goodsDetail.value.skus[i].specs[0].valueName === colorValue.value &&
            goodsDetail.value.skus[i].specs[1].valueName === sizeValue.value
          ) {
            idstr.value = goodsDetail.value.skus[i].id
            break
          }
        }
      } else {
        if (goodsDetail.value.skus[i].specs[0].valueName === colorValue.value) {
          idstr.value = goodsDetail.value.skus[i].id
          break
        }
      }
    }
    //将获取到的id信息传入接口
    try {
      const response = await addToCartAPI(idstr.value, product.count)
      if (response.status === 200) {
        store1.getCartCount()
        ElMessage.success('加入购物车成功')
      }
    } catch (error) {
      ElMessage.error('请选择完整规格')
    }
  }
}

//定义响应式的产品信息对象
const product = reactive({
  //默认位置
  location: '北京市 市辖区 东城区',
  count: 1
})

//获取热销商品
const dayhotsellings = ref({})
const getDayHotSellingData = async () => {
  const res = await getHotSellingAPI(1)
  dayhotsellings.value = res.data.result
}
const weekhotsellings = ref({})
const getWeekHotSellingData = async () => {
  const res = await getHotSellingAPI(2)
  weekhotsellings.value = res.data.result
}
const { target: hotSellingTarget } = lazyApi(getDayHotSellingData)
const { target: weekHotSellingTarget } = lazyApi(getWeekHotSellingData)

// 监听路由
watch(
  () => route.params.id,
  () => {
    loading.value = true
    getGoodsDetail()
  }
)
</script>

<template>
  <div class="outer-container">
    <div class="container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/category/${idstr1}` }">{{ nag1 }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/category/sub/${idstr2}` }">{{
          nag2
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ goodsDetail.name }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="goods-info" v-loading="loading" element-loading-text="玩命加载中...">
        <div class="media">
          <GoodsImage :images="goodsDetail.mainPictures" />
          <ul class="goods-sales">
            <li>
              <p>销量人气</p>
              <p>200+</p>
              <p>
                <i class="iconfont icon-task-filling"></i>
                销量人气
              </p>
            </li>
            <li>
              <p>商品评价</p>
              <p>400+</p>
              <p>
                <i class="iconfont icon-comment-filling"></i>
                查看评价
              </p>
            </li>
            <li>
              <p>收藏人气</p>
              <p>600+</p>
              <p @click="collectGoods(route.params.id)" style="cursor: pointer">
                <i class="iconfont icon-favorite-filling"></i>
                收藏商品
              </p>
            </li>
            <li>
              <p>品牌信息</p>
              <p>苏宁电器</p>
              <p>
                <i class="iconfont icon-dynamic-filling"></i>
                品牌主页
              </p>
            </li>
          </ul>
        </div>
        <div class="spec">
          <p class="g-name">{{ goodsDetail.name }}</p>
          <p class="g-desc">{{ goodsDetail.desc }}</p>
          <p class="g-price">
            <span>{{ goodsDetail.price }}</span>
            <span>{{ goodsDetail.oldPrice }}</span>
          </p>
          <div class="g-service">
            <dl>
              <dt>促销</dt>
              <dd>12月好物放送，App领券购买直降120元</dd>
            </dl>
            <dl>
              <dt>配送</dt>
              <dd>
                <b style="vertical-align: middle; padding-right: 5px; font-weight: normal">至</b>
                <CitySelector :location="product.location" />
              </dd>
            </dl>
            <dl>
              <dt>服务</dt>
              <dd>
                <span>无忧退货</span>
                <span>快速退款</span>
                <span>免费包邮</span>
                <a href="javascript:;">了解详情</a>
              </dd>
            </dl>
          </div>
          <div class="goods-sku">
            <div v-for="sku in goodsDetail.specs" :key="sku">
              <dl v-if="sku.values[0].picture !== null">
                <dt>{{ sku.name }}</dt>
                <dd>
                  <img
                    :class="{ active: i === currIndex }"
                    v-for="(color, i) in sku.values"
                    :key="color.picture"
                    @click.prevent="colorValueFun(color.name, i)"
                    :src="color.picture"
                  />
                </dd>
              </dl>
              <dl v-else>
                <dt>{{ sku.name }}</dt>
                <dd>
                  <span
                    v-for="(skuv, i) in sku.values"
                    :key="skuv"
                    @click.prevent="sizeValueFun(skuv.name, i)"
                    :class="{ active: i === currIndex2 }"
                  >
                    {{ skuv.name }}
                  </span>
                </dd>
              </dl>
            </div>
          </div>
          <InputNumber v-model="product.count">数量</InputNumber>
          <button class="button" @click="addToCart">加入购物车</button>
        </div>
      </div>
      <div class="goods-relevant">
        <div class="header" ref="recommendTarget">
          <i class="icon"></i><span class="title">同类商品推荐</span>
        </div>
        <GoodsCarousel :products="recommendsDetail" />
      </div>
      <div class="content-row">
        <ReviewAndDetails class="good-details"></ReviewAndDetails>
        <div class="hot-selling">
          <div class="hot-selling-title" ref="hotSellingTarget">24小时热销榜</div>
          <HotSelling :hotsellings="dayhotsellings"></HotSelling>
          <div class="hot-selling-title" ref="weekHotSellingTarget">周热销榜</div>
          <HotSelling :hotsellings="weekhotsellings"></HotSelling>
        </div>
      </div>
      <NoticeList></NoticeList>
    </div>
  </div>
</template>

<style lang="less" scoped>
.outer-container {
  background-color: #f5f5f5;
  padding: 25px;
  display: flex;
  justify-content: center;
}

.container {
  width: 1240px;
  margin: 0 auto;
  position: relative;
  caret-color: transparent;
}

.breadcrumb {
  font-size: 15px;
  margin-bottom: 25px;
  a {
    color: #333;
    text-decoration: none;
  }
  .el-breadcrumb__inner {
    color: #999;
  }
  .el-breadcrumb__separator {
    margin: 0 8px;
  }
}
.goods-info {
  min-height: 600px;
  background: #fff;
  display: flex;

  .media {
    width: 580px;
    height: 600px;
    padding: 30px 50px;
  }

  .spec {
    flex: 1;
    padding: 30px 30px 30px 0;
  }
}

.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
}

.goods-sales {
  display: flex;
  width: 400px;
  align-items: center;
  text-align: center;
  height: 140px;
  list-style: none;
  font-size: 14px;

  li {
    flex: 1;
    position: relative;

    p:first-child {
      color: #999;
    }

    p:nth-child(2) {
      color: #cf4444;
      margin-top: 10px;
    }

    p:last-child {
      color: #666;
      margin-top: 10px;

      i {
        color: #27ba9b;
      }
    }

    p:last-child:hover {
      color: #27ba9b;
      /* 悬浮时改变文字颜色 */
    }
  }
}

.spec {
  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }
}

.g-price {
  margin-top: 10px;

  span::before {
    content: '¥';
    font-size: 14px;
  }

  span:first-child {
    color: #cf4444;
    margin-right: 10px;
    font-size: 22px;
  }

  span:last-child {
    color: #999;
    text-decoration: line-through;
    font-size: 16px;
  }
}

.g-service {
  background: #f5f5f5;
  width: 500px;
  padding: 20px 10px 0 10px;
  margin-top: 10px;
  font-size: 14px;

  dl {
    padding-bottom: 20px;
    display: flex;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      color: #666;

      &:last-child span {
        margin-right: 10px;

        &::before {
          content: '•';
          color: #27ba9b;
          margin-right: 2px;
        }
      }

      a {
        color: #27ba9b;
        text-decoration: none;
        outline: none;
      }
    }
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  font-size: 14px;

  dl {
    display: flex;
    padding-bottom: 10px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;
      line-height: 40px;
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      gap: 10px;

      span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        border: 1px solid #e4e4e4;
        margin-right: 10px;

        &.active {
          border: 2px solid #27ba9b;
        }
      }

      img {
        width: 50px;
        height: 50px;
        margin-bottom: 5px;
        border: 1px solid #e4e4e4;
        margin-right: 10px;

        &.active {
          border: 2px solid #27ba9b;
        }
      }
    }
  }
}

.button {
  margin-top: 20px;
  border-color: #27ba9b;
  background: #27ba9b;
  color: #fff;
  width: 180px;
  height: 50px;
  font-size: 16px;
  text-align: center;
  border: 1px solid transparent;
  border-radius: 4px;
  outline: none;
  appearance: none;
}

.goods-relevant {
  background: #fff;
  min-height: 460px;
  margin-top: 20px;

  .header {
    height: 80px;
    line-height: 80px;
    padding: 0 20px;

    .title {
      font-size: 20px;
      padding-left: 10px;
    }

    .icon {
      width: 16px;
      height: 16px;
      display: inline-block;
      border-top: 4px solid #27ba9b;
      border-right: 4px solid #27ba9b;
      box-sizing: border-box;
      position: relative;
      transform: rotate(45deg);

      &::before {
        content: '';
        width: 10px;
        height: 10px;
        position: absolute;
        left: 0;
        top: 2px;
        background: #bcf1e6;
      }
    }
  }
}

.content-row {
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-bottom: 20px;
  min-height: 2750px;
  margin-top: 20px;
}

.hot-selling {
  margin-left: 20px;
  width: 20%;
  height: 200px;
}

.hot-selling-title {
  background-color: rgb(226, 98, 55);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px;
  width: 95%;
  height: 70px;
  font-size: 20px;
}

.good-details {
  width: 80%;
}

@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.eot');
  /* IE9 */
  src: url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.eot#iefix') format('embedded-opentype'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.woff2') format('woff2'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.woff') format('woff'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.ttf') format('truetype'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.svg#iconfont') format('svg');
}

.iconfont {
  font-family: 'iconfont' !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-backtop:before {
  content: '\e622';
}
.icon-comment-filling:before {
  content: '\e689';
}
.icon-dynamic-filling:before {
  content: '\e68a';
}
.icon-favorite-filling:before {
  content: '\e68b';
}
.icon-task-filling:before {
  content: '\e68c';
}
.icon-close-new:before {
  content: '\e668';
}
.icon-bind:before {
  content: '\e63f';
}
.icon-edit:before {
  content: '\e615';
}
.icon-msg:before {
  content: '\e62d';
}
.icon-fenxiang:before {
  content: '\e60f';
}
.icon-duigou:before {
  content: '\e605';
}
.icon-order-comment:before {
  content: '\e60a';
}
.icon-angle-down:before {
  content: '\e7b5';
}
.icon-order-deliver:before {
  content: '\e64a';
}
.icon-shanchu:before {
  content: '\e613';
}
.icon-see:before {
  content: '\e6ee';
}
.icon-chakan2:before {
  content: '\e6ef';
}
.icon-queren:before {
  content: '\e6f8';
}
.icon-queren2:before {
  content: '\e6f9';
}
.icon-hart1:before {
  content: '\e711';
}
.icon-hart2:before {
  content: '\e712';
}
.icon-message:before {
  content: '\e7b4';
}
.icon-code:before {
  content: '\e656';
}
.icon-position:before {
  content: '\e61e';
}
.icon-weixin:before {
  content: '\e62e';
}
.icon-order-receive:before {
  content: '\e6b1';
}
.icon-weibo:before {
  content: '\e63e';
}
.icon-angle-right:before {
  content: '\e612';
}
.icon-angle-left:before {
  content: '\e614';
}
.icon-unchecked:before {
  content: '\e626';
}
.icon-checked:before {
  content: '\e627';
}
.icon-cart:before {
  content: '\e60c';
}
.icon-lock:before {
  content: '\e6e9';
}
.icon-tip:before {
  content: '\e628';
}
.icon-order-complete:before {
  content: '\e666';
}
.icon-warning:before {
  content: '\e763';
}
.icon-guanbi:before {
  content: '\e608';
}
.icon-hy:before {
  content: '\e74a';
}
.icon-dw:before {
  content: '\e751';
}
.icon-aq:before {
  content: '\e753';
}
.icon-phone:before {
  content: '\e633';
}
.icon-dianzan:before {
  content: '\e719';
}
.icon-search:before {
  content: '\e6c7';
}
.icon-question:before {
  content: '\e675';
}
.icon-wjx02:before {
  content: '\e629';
}
.icon-wjx01:before {
  content: '\e62b';
}
.icon-order-unpay:before {
  content: '\e635';
}
.icon-kefu:before {
  content: '\e625';
}
.icon-safe:before {
  content: '\e60d';
}
.icon-down-time:before {
  content: '\e609';
}
.icon-footer01:before {
  content: '\e602';
}
.icon-footer03:before {
  content: '\e600';
}
.icon-footer02:before {
  content: '\e601';
}
.icon-xiaoxi:before {
  content: '\e61a';
}
.icon-user:before {
  content: '\e655';
}
.icon-order-cancel:before {
  content: '\e61b';
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #f5f5f5;
}

html {
  font-family: 'Microsoft Yahei', 'PingFang SC', Avenir, 'Segoe UI';
  line-height: 1.4;
}
</style>
